let fs = require("fs");
let url = require("url");
let http = require("http");

let server = http.createServer((request,response) => {
    let urlObj = url.parse(request.url,true);
    response.setHeader("content-type","text/html;charset=utf-8");

    // 登录
    if(urlObj.pathname == "/login"){
        response.end(fs.readFileSync("./code/views/login.html").toString("utf-8"));
        return;
    }

    // 注册
    if(urlObj.pathname == "/register"){
        response.end(fs.readFileSync("./code/views/register.html").toString("utf-8"));
        return;
    }

    // 点击注册按钮
    if(urlObj.pathname == "/doregister"){
        let {query:{username,password}} = urlObj;
        // 读取文件内容
        let read = fs.readFileSync("./code/persons.json");
        // 字符串转数组
        let arr = JSON.parse(read);
        let findNum = arr.findIndex((a) => {
            return a.username == username;
        })
        if(findNum != -1){
            response.end("<h1>该账号已被注册</h1>");
        }else{
            arr.push({username,password});
            // 数组转字符串
            let str = JSON.stringify(arr);
            fs.writeFileSync("./code/persons.json",str);
            response.end("<h1>注册成功</h1>");
        }
        
        return;
    }


    // 点击登录
    if(urlObj.pathname == "/dologin"){
        // 获取输入内容
        let {query:{username,password}} = urlObj;
        // 读取文件内容
        let read = fs.readFileSync("./code/persons.json");
        // 字符串转数组
        let arr = JSON.parse(read);
        let findNum = arr.findIndex((a) => {
            return a.username == username && a.password == password;
        })
        if(findNum != -1){
            response.end("<h1>登录成功</h1>");
        }else{
            response.end("<h1>账号或者密码不正确</h1>");
        }
        return;
    }


    response.end("<h1>未找到网页，网址不正确</h1>");

})

// 启动http服务监听
server.listen(3000,() => {
    console.log("服务器已开启，搞起来");
});